import authRoutes from '../../router/authRoutes'
import otherRoutes from '../../router/otherRoutes'
import { getAdminMenuList } from 'api/commonApi'
// let pingPuArr = []
// function dasan (arr) {
//   arr.forEach(item => {
//     pingPuArr.push(item)
//     if (item.childs.length > 0) {
//       dasan(item.childs)
//     }
//   })
//   return pingPuArr
// }
const iconObj = {
  sysManagement: 'icon-shezhi',
  lineManagement: 'icon-dibudaohanglan-',
  memberManagement: 'icon-xinbaniconshangchuan-',
  marketingManagement: 'icon-yingxiao'
}

function addicon(arr){
  arr.forEach(item => {
    let icon = iconObj[item.menuENName]
    if(icon){
      item.icon = icon
    }
  })
}

export default {
  async getMenu ({ commit }) {
    try {
      // let res = await getMenuList()
      let res = await getAdminMenuList()

      // let data = dasan(res.rData)
      let data = res
      console.log(data)
      addicon(data)
      // 平铺获得的菜单
      let pingPuArr = data
      // 过滤没有权限的菜单
      // eslint-disable-next-line
      function myfilter (arr) {
        let myArr = arr.filter(item => {
          if (item.auth === 'home') {
            // item.component = item.component()
            if (item.children && item.children.length > 0) {
              item.children = myfilter(item.children)
            } else {
              item.children = null
            }
            return true
          } else {
            let hasMenu = pingPuArr.some(item2 => {
              if (item2.menuENName === item.auth) {
                if(!item.meta){
                  item.meta = {}
                }
                item.meta.menuZHName = item2.menuZHName
                return true
              }
              return false
            })
            if (hasMenu) {
              // item.component = item.component()
              if (item.children && item.children.length > 0) {
                item.children = myfilter(item.children)
              } else {
                item.children = null
              }
            }
            return hasMenu
          }
        })
        return myArr
      }
      let afterRoutes = myfilter(authRoutes).concat(otherRoutes)
      console.log('afterRoutes', afterRoutes, JSON.parse(JSON.stringify(data)) )
      // eslint-disable-next-line
      function saveTree(pid){
        return data.filter(item => {
          if(item.up_menu_id === pid){
            item.children = saveTree(item.menu_id)
            return true
          }
          return false
        })
      }

      commit('saveTreeRoutes', saveTree(0))
      return afterRoutes
    } catch (error) {
      // 获取菜单失败 会递归
      commit('saveTreeRoutes', [].concat(otherRoutes) )
    }
  }
}
